package util;

import global.Constants;
import global.SendEmail;
import global.security.BasicAuthenticator;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

/**
 * Servlet处理公共类.
 * <p>
 * 创建日期：2010-07-01<br>
 * 创建人：Xiyt<br>
 * 修改日期：<br>
 * 修改人：<br>
 * 修改内容：<br>
 * 
 * @author Xiyt
 * @version 1.0
 */
public class ServletHelp {

	/**
	 * 回写json格式的结果
	 * 
	 * @param request
	 * @return
	 */
	public static void outRequestForJson(HttpServletRequest request,
			HttpServletResponse response, String res) throws IOException {
		response.setContentType("application/x-json; charset=UTF-8");
		response.getWriter().print(res);
	}

	/**
	 * 获得服务器真实路径
	 * 
	 * @param request
	 * @return
	 */
	public static String getRealPath(HttpServletRequest request,
			String virtualPath) {
		return request.getSession().getServletContext()
				.getRealPath(virtualPath);
	}

	/**
	 * 从request中获得参数Map，并返回可读的Map
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Map getParameterMap(HttpServletRequest request) {
		// 参数Map
		Map properties = request.getParameterMap();
		// 返回值Map
		Map returnMap = new HashMap();
		Iterator entries = properties.entrySet().iterator();
		Map.Entry entry;
		String name = "";
		String value = "";
		while (entries.hasNext()) {
			entry = (Map.Entry) entries.next();
			name = (String) entry.getKey();
			Object valueObj = entry.getValue();
			if(null == valueObj){
				value = "";
			}else if(valueObj instanceof String[]){
				String[] values = (String[])valueObj;
				for(int i=0;i<values.length;i++){
					value = values[i] + ",";
				}
				value = value.substring(0, value.length()-1);
			}else{
				value = valueObj.toString();
			}
			returnMap.put(name, value);
		}
		return returnMap;
	}
	
	
	/**
	 * 把Map转换成javascript数组
	 * 
	 * @param map 要转行的Map
	 * @param emptyText 设置空值显示的文本，为空是不添加空选项
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static String getArrayFromMap(Map map, String needEmpty){
		if(null == map){
			return null;
		}
		StringBuffer sb = null;
		if(StringUtils.isNotEmpty(needEmpty)){
			sb = new StringBuffer("[[\'\', \'"+needEmpty+"\'],");
		}else{
			sb = new StringBuffer("[");
		}
		Set<String> keySet = map.keySet();
		Iterator<String> ite = keySet.iterator();
		String key = "";
		while (ite.hasNext()) {
			key = ite.next();
			sb.append("[\'"+key+"\', \'"+map.get(key)+"\'],");
		}
		String rs = sb.toString();
		if(rs.endsWith(",")){
			rs = rs.substring(0, rs.length()-1);
		}
		return rs+="]";
	}

	/**
	 * 下载
	 * 
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @param url
	 *            文件链接
	 * @param fileName
	 *            文件名
	 * @return ActionForward
	 */
	public static ActionForward download(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response, String url, String fileName)
			throws Exception {
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
				url));
		// 设置保存文件时的文件名
		fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
		response.setHeader("Content-Disposition", "attachment;filename="
				+ fileName);
		// 设置文件类型
		response.setContentType("application/x-msdownload");

		// 输出流
		ServletOutputStream sos = response.getOutputStream();
		BufferedOutputStream bos = new BufferedOutputStream(sos);
		byte[] buffer = new byte[1024];
		int len = -1;
		while ((len = bis.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}

		// 关闭流
		if (null != bos) {
			bos.close();
		}
		if (null != sos) {
			sos.close();
		}
		if (null != bis) {
			bis.close();
		}

		return null;
	}

	/**
	 * 打包下载
	 * 
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @param url
	 *            文件链接
	 * @param fileName
	 *            文件名
	 * @return ActionForward
	 */
	public static ActionForward downloadZip(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response, String urls[], String fileNames[])
			throws Exception {
		// 一时间作为压缩文件名
		String zipFileName = DateUtils
				.formatDate2Str(DateUtils.DATE_TIME_PATTON_3);
		// 设置头信息
		response.setContentType("application/x-zip-compressed");
		response.setHeader("Content-Disposition", "inline; filename="
				+ zipFileName + ".zip");

		// 压缩输出流
		int size = urls.length;
		ZipOutputStream zipOutput = new ZipOutputStream(response
				.getOutputStream());
		zipOutput.setMethod(ZipOutputStream.DEFLATED);
		zipOutput.setEncoding("UTF-8");
		for (int i = 0; i < size; i++) {
			zipOutput.putNextEntry(new ZipEntry(fileNames[i]));
			writeZipStream(zipOutput, new FileInputStream(new File(urls[i])));
			zipOutput.flush();
			response.flushBuffer();
		}
		if (null != zipOutput) {
			zipOutput.close();
		}
		return null;
	}

	/**
	 * 发送邮件
	 * 
	 * @param emails
	 *            用','分隔的邮箱地址
	 * @param title
	 *            邮件标题
	 * @param content
	 *            邮件内容
	 */
	public static boolean sendEmail(String emails, String title, String content)
			throws Exception {
		// 返回值
		boolean result = false;
		if (StringUtils.isNotEmpty(emails)) {
			title = Constants.EMAIL_BEFORE_TITLE + title;
			String[] emailArr = emails.split(",");
			if (emailArr != null) {
				for (int i = 0; i < emailArr.length; i++) {
					SendEmail sendEmail = new SendEmail(emailArr[i], title,
							content);
					result = sendEmail.execSend();
				}
			}
		}
		return result;
	}

	/**
	 * 将inputStream放入ZipOutputStream
	 * 
	 * @param zipOutput
	 * @param in
	 * @throws Exception
	 */
	private static void writeZipStream(ZipOutputStream zipOutput, InputStream in)
			throws Exception {
		if (in == null) {
			return;
		}
		byte b[] = new byte[1024 * 5];
		int len = 0;
		while ((len = in.read(b)) != -1) {
			zipOutput.write(b, 0, len);
		}
		in.close();
	}

	/**
	 * 获得http连接
	 * @param url URL
	 * @return http连接
	 * @throws Exception
	 */
	public static HttpURLConnection getHttpConnection(String url) throws Exception {
	    URL u = new URL(url);
	    if ("2".equals(Constants.NETWORK_TYPE)){
	        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(Constants.PROXY_IP, Constants.PROXY_PORT)); 
	        HttpURLConnection httpConn = (HttpURLConnection) u.openConnection(proxy);

	        // 代理身份验证
	        if (StringUtils.isNotEmpty(Constants.PROXY_USER)) {
	            Authenticator.setDefault(new BasicAuthenticator(Constants.PROXY_USER, Constants.PROXY_PASSWORD));
	        }
	        return httpConn;
	    } else {
	        return (HttpURLConnection) u.openConnection(); 
	    }
	}
}
